import logging

from plyne.lib.base import *

log = logging.getLogger(__name__)

from plyne.model import model_classes


class PageController(BaseController):

    def index(self, title):
        page_q = Session.query(model_classes['Content'])
        page = page_q.filter_by(id=title).first()

        if page:
            c.title = page.title
            c.contents = self.list()
            c.description = page.description

            full_page = self.get_elem(page.content_id)
            if full_page and hasattr(full_page, 'text'):
                c.text = full_page.text
            else:
                c.text = ''

            return render('/page.mako')
        abort(404)


    def list(self):
        page_q = Session.query(model_classes['Content'])
        contents = [(page.title, page.id) for page in Session.query \
                   (model_classes['Content']).all()]
        return contents


    def get_elem(self, id):
        """Very ugly method to get a item given an id, this should
           be improved and avoid iterating over all the tables, not
           better implementation made yet"""
        for a_class in model_classes:
            page_q = Session.query(model_classes[a_class])   
            try:
                page = page_q.filter_by(content_id=id).first()       
            except:
                pass

            if page:
                return page

        return 0

